package fr.epsi.activities.tache;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.example.MyLittleHotel.R;
import fr.epsi.BDD.BDD;
import fr.epsi.fragment.pickers.DatePickerFragment;
import fr.epsi.fragment.pickers.TimePickerFragment;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Florent Baudon on 22/05/2014.
 */
public class AjouterTacheActivity extends FragmentActivity implements View.OnClickListener, TimePickerFragment.ValidTimeSetListener, DatePickerFragment.ValidDateSetListener {

    private BDD bdd;

    private Button ajouter;
    private EditText label, heureDebut, heureFin, date;
    private Spinner emp, service;
    private String empSelect, serviceSelect;
    private DialogFragment fragHeureDeb, fragHeureFin, fragDate;

    public void onCreate(Bundle savedInstanceState) {
        bdd = new BDD();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ajoutertachelayout);

        ajouter = (Button)findViewById(R.id.ajouterTache);

        label = (EditText)findViewById(R.id.labelTache);
        emp = (Spinner)findViewById(R.id.empTache);
        heureDebut = (EditText)findViewById(R.id.heureDeb);
        heureFin = (EditText)findViewById(R.id.heureFin);
        date = (EditText)findViewById(R.id.date);

        ajouter.setOnClickListener(this);
        heureDebut.setOnClickListener(this);
        heureFin.setOnClickListener(this);
        date.setOnClickListener(this);

        //ajout et config du spinner employé
        emp = (Spinner)findViewById(R.id.empTache);
        List<String> empList = setEmpService();
        ArrayAdapter<String> spinnerAdaptEmp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, empList);
        spinnerAdaptEmp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        emp.setAdapter(spinnerAdaptEmp);
        emp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
               empSelect = (String)adapterView.getItemAtPosition(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        //Ajout et config du spinner
        service = (Spinner)findViewById(R.id.serviceTache);
        List<String> servicesList = setListService();
        ArrayAdapter<String> spinnerAdaptServ= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, servicesList);
        spinnerAdaptServ.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        service.setAdapter(spinnerAdaptServ);
        service.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                serviceSelect = (String)adapterView.getItemAtPosition(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    @Override
    public void onClick(View v) {
       //Declenchement des fragment pour les date et time pickers.
        if(v==heureDebut) {
            fragHeureDeb = new TimePickerFragment();
            FragmentManager fm = getSupportFragmentManager();
            fragHeureDeb.show(fm, "Time Picker");
        }
        if(v==heureFin) {
            fragHeureFin = new TimePickerFragment();
            FragmentManager fm = getSupportFragmentManager();
            fragHeureFin.show(fm, "Time Picker");
        }
        if(v== date){
            fragDate = new DatePickerFragment();
            FragmentManager fm = getSupportFragmentManager();
            fragDate.show(fm, "Date Picker");
        }

        if(v==ajouter){
            //Separation nom et prenom
            String nom = empSelect.substring(0, empSelect.indexOf(" "));
            String prenom = empSelect.substring(empSelect.indexOf(" ")+1, empSelect.length());
            boolean tacheSuperpos = this.trouverTachesSuperpose(nom, prenom);
            boolean absenceSuperpos = this.trouverAbsencesSuperpose(nom, prenom);
            if(!tacheSuperpos && !absenceSuperpos) {
                //insertion dans la base de donnée
                try {
                    bdd.open(this);
                    bdd.insertTache(label.getText().toString(), serviceSelect,
                            nom, prenom, date.getText().toString() + " " + heureDebut.getText().toString(),
                            date.getText().toString() + " " + heureFin.getText().toString());
                    bdd.closeBDD();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                label.setText("");

                heureDebut.setText("");
                heureFin.setText("");
                date.setText("");
                Toast t = Toast.makeText(this, "Tâche ajoutée", Toast.LENGTH_SHORT);
                t.show();
            }else{
                if(tacheSuperpos) {
                    Toast t = Toast.makeText(this, "Employé déjà assigné à une tâche", Toast.LENGTH_SHORT);
                    t.show();
                }else if(absenceSuperpos){
                    Toast t = Toast.makeText(this, "Employé absent", Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        }
    }

    @Override
    public void ValidTimeSet(DialogFragment df, int heure, int min) {

        String h = String.valueOf(heure);
        String m = String.valueOf(min);

        if(h.length()==1)
            h = "0"+ h;
        if(m.length()==1)
            m = "0"+ m;

        if(df==fragHeureDeb) {
            heureDebut.setText(h + ":" + m);
        }
        if(df==fragHeureFin) {
            heureFin.setText(h + ":" + m);
        }
    }

    @Override
    public void validDateSet(DialogFragment df, int an, int mois, int jour) {
        //car android commence le calendrier au mois 0, donc janvier = 0, fevriers=1 etc...
        mois++;
        String m = String.valueOf(mois);
        String j = String.valueOf(jour);

        if(m.length()==1)
            m = "0" + m;
        if(j.length()==1)
            j = "0" + j;

        date.setText(an + "/" + m + "/" + j);
    }

    //récupére la liste des service pour le spinner
    private List<String> setEmpService(){
        Cursor cListEmp;
        try{
            bdd.open(this);
        }catch (SQLException e){
            e.printStackTrace();
        }
        cListEmp = bdd.getEmployes();

        List<String> serviceList = new ArrayList<String>();

        if(cListEmp!=null && cListEmp.moveToFirst()){
            boolean finish=false;
            while(!finish) {
                serviceList.add(cListEmp.getString(1) + " " + cListEmp.getString(2));
                if (cListEmp.isLast())
                    finish = true;
                else
                    cListEmp.moveToNext();
            }
        }
        bdd.closeBDD();
        return serviceList;
    }

    //récupére la liste des service pour le spinner
    private List<String> setListService(){
        Cursor cListServices;
        try{
            bdd.open(this);
        }catch (SQLException e){
            e.printStackTrace();
        }
        cListServices = bdd.getServices();

        List<String> serviceList = new ArrayList<String>();

        if(cListServices!=null && cListServices.moveToFirst()){
            boolean finish=false;
            while(!finish) {
                serviceList.add(cListServices.getString(1));
                if (cListServices.isLast())
                    finish = true;
                else
                    cListServices.moveToNext();
            }
        }
        bdd.closeBDD();
        return serviceList;
    }

    private boolean trouverTachesSuperpose(String nom, String prenom){
        boolean superpose = false;
        try {
            bdd.open(this);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        Cursor cListTache = bdd.getTachesEmploye(nom, prenom);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        Date dateDebBDD=null, dateFinBDD=null, dateDebEntree=null, dateFinEntree=null;
        //on convertie les dates entrée en Date
        try {
            dateDebEntree = sdf.parse(date.getText().toString() + " " + heureDebut.getText().toString());
            dateFinEntree = sdf.parse(date.getText().toString() + " " + heureFin.getText().toString());
        }catch (ParseException e){
            e.printStackTrace();
        }

        //si le cursor est pas null et est au début
        if(cListTache!=null && cListTache.moveToFirst()){
            while(!cListTache.isAfterLast()) {
                //On recupere les  date de début et de fin  pour chaque tâche, on les convertie au format date et on les compare ensuite au date entrées
                for (int i = 0; i < cListTache.getColumnCount(); i++) {
                    try {
                        if(i==0)
                            dateDebBDD = sdf.parse(cListTache.getString(i));
                        if(i==1)
                            dateFinBDD = sdf.parse(cListTache.getString(i));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if((dateDebBDD.before(dateDebEntree) && dateFinBDD.after(dateDebEntree))
                        || (dateDebBDD.before(dateFinEntree) && dateFinBDD.after(dateFinEntree))
                        || (dateDebBDD.before(dateDebEntree) && dateFinBDD.after(dateFinEntree))
                        || (dateDebBDD.after(dateDebEntree) && dateFinBDD.before(dateFinEntree))){

                    superpose=true;
                }
                cListTache.moveToNext();
            }
        }
        bdd.closeBDD();
        return superpose;
    }

    private boolean trouverAbsencesSuperpose(String nom, String prenom){
        boolean superpose = false;
        try {
            bdd.open(this);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        Cursor cListAbs= bdd.getAbsencesEmploye(nom, prenom);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        Date dateDebBDD=null, dateFinBDD=null, dateDebEntree=null, dateFinEntree=null;
        //on convertie les dates entrée en Date
        try {
            dateDebEntree = sdf.parse(date.getText().toString() + " " + heureDebut.getText().toString());
            dateFinEntree = sdf.parse(date.getText().toString() + " " + heureFin.getText().toString());
        }catch (ParseException e){
            e.printStackTrace();
        }
        Log.i("TEST", "top avt " + cListAbs.getColumnCount() + " " + cListAbs.getCount());
        //si le cursor est pas null et est au début
        if(cListAbs != null && cListAbs.moveToPosition(0)){
            Log.i("TEST", "top abs");
            while(!cListAbs.isAfterLast()) {
                //On recupere les  date de début et de fin  pour chaque tâche, on les convertie au format date et on les compare ensuite au date entrées
                for (int i = 0; i < cListAbs.getColumnCount(); i++) {
                    try {
                        if(i==0) {
                            dateDebBDD = sdf.parse(cListAbs.getString(i));
                            Log.i("Format ABSBDD",cListAbs.getString(i));
                        }
                        if(i==1)
                            dateFinBDD = sdf.parse(cListAbs.getString(i));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if((dateDebBDD.before(dateDebEntree) && dateFinBDD.after(dateDebEntree))
                        || (dateDebBDD.before(dateFinEntree) && dateFinBDD.after(dateFinEntree))
                        || (dateDebBDD.before(dateDebEntree) && dateFinBDD.after(dateFinEntree))
                        || (dateDebBDD.after(dateDebEntree) && dateFinBDD.before(dateFinEntree))){

                    superpose=true;
                }
                cListAbs.moveToNext();
            }
        }
        bdd.closeBDD();
        return superpose;
    }
}